#source ./exec_output.sh
#source ./exec_backup.sh
source ./exec_sql.sh
source ./exec_ptosc.sh
source ./function.sh
source ./variables.sh






# 检查当前实例和 sql 是否支持使用 pt-osc
shunt_alter() {
    local check_status=0
    local sql_info="$1"

    # 检查 mysql 版本
    check_mysql_version(){
        local mysql_version=$($MYSQL_CONN -N -e "select @@version" 2>/dev/null|awk -F. '{print $1$2}')
        if [ $mysql_version -lt 55 ];then
            check_status=1
        fi
    }
    check_mysql_version

    # 检查表存储引擎
    check_table_engine(){
        local table_name="$(sql_processing "table_name" "$sql_info")"
        local table_engine="$($MYSQL_CONN -N -e "SELECT ENGINE FROM information_schema.TABLES WHERE TABLE_SCHEMA = '$MYSQL_DATABASE' AND TABLE_NAME = '$table_name';" 2>/dev/null)"
        if [ "$table_engine" != "InnoDB" ];then
            log_message "${table_name} 表的存储引擎为 ${table_engine}" 'warning' 0
            check_status=1
        fi  
    }
    check_table_engine

    # 检查主键或唯一键
    check_table_unique_or_primary_key(){
        local table_name="$(sql_processing "table_name" "$sql_info")"
        local table_unique_or_primary_key="$($MYSQL_CONN -N -e  "SELECT CONSTRAINT_TYPE FROM information_schema.TABLE_CONSTRAINTS WHERE TABLE_SCHEMA = '$MYSQL_DATABASE'  AND TABLE_NAME = '$table_name'  AND (CONSTRAINT_TYPE = 'PRIMARY KEY' OR CONSTRAINT_TYPE = 'UNIQUE');" 2>/dev/null)"
        if  [ -z "$table_unique_or_primary_key" ];then
            log_message "$table_name 表没有主键或唯一键" "warning" 0
            check_status=1
        fi
    }
    check_table_unique_or_primary_key
    

    # 检查触发器
    check_trigger() {
        # 5.7.2之前表上有触发器无法使用 pt-osc
        local table_name="$(sql_processing "table_name" "$sql_info")"
        local check_mysql_version="$($MYSQL_CONN -N -e "select SUBSTRING_INDEX(VERSION(), '-', 1" 2>/dev/null |awk -F'.' '{printf "%d%d%02d\n", $1,$2,$3}' )"

        if [ $check_mysql_version -lt 5702 ];then
            local sql_info="SELECT COUNT(*) FROM information_schema.triggers WHERE event_object_schema = '$MYSQL_DATABASE' AND event_object_table = '$table_name';"
            local check_trigger=$($MYSQL_CONN -N -e "$sql_info" 2>/dev/null)
            if [ $check_trigger -gt 0 ];then
                log_message "5.7.2 之前版本表包含触发器 无法使用 pt-osc: $sql_info" "warning" 1
                check_status=1
            fi  
        fi
    }

    # 检查删除外键
    check_drop_foreign_key() {
        local check_drop_foreigin_key=$(echo "$sql_info"|egrep  -ic 'drop\s+foreign')
        if [ $check_drop_foreigin_key -gt 0 ];then
            check_status=1
        fi
    }
    check_drop_foreign_key

    # 检查重命名表
    check_rename_table(){
        local check_rename_table=$(echo "$sql_info"|egrep  -ic 'rename\s+to')
        if [ $check_rename_table -gt 0 ];then
            check_status=1
        fi
    }
    check_rename_table

    # 等于 1 可以使用 pt-osc
    if [ $check_status -ne 0 ];then
        echo 0
    else
        echo 1
    if 
}
 








